package com.google.zxing.client.android;

import haseman.project.Geonames.GeonameClient;
import haseman.project.Geonames.GeonameObject;

import haseman.project.where4.CustomCameraView;

import java.util.ArrayList;
import java.util.Currency;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

import org.geonames.Toponym;
import org.geonames.WebService;

import com.google.zxing.client.android.share.ShareActivity;

import ARKit.ARLayout;
import ARKit.TransparentPanel;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import haseman.project.Geonames.GeonamesWebService;

public class Main extends Activity {
	/** Called when the activity is first created. */
	CustomCameraView cv;
	public static volatile Context ctx;
	public static Location curLocation = null;
	public static FrameLayout rl;
	public static AbsoluteLayout al;
	static ARLayout ar;

	List<Thread> threadList = new ArrayList<Thread>();
	public List<Toponym> indoorPlaces = new ArrayList<Toponym>();
	Vector<GeonameObject> vc;
	boolean connected = false;

	String username;
	String password;
	String query;

	Bundle bundle;

	public static ScrollView scrollView;
	public static LinearLayout linearLayout;

	Button buttonClicked;
	public static TextView textView;
	TransparentPanel transPanel;
	EditText editText;
	Button addCommentButton;
	String comments;

	public static Button buttonPlace1Button;
	public static Button buttonPlace2Button;
	public static Button buttonPlace3Button;
	public static Button buttonPlace4Button;
	public static Button buttonPlace5Button;
	public static Button buttonPlace6Button;
	public static Button buttonPlace7Button;
	public static Button buttonPlace8Button;
	public static Button buttonPlace9Button;
	public static Button buttonPlace10Button;

	public static LinearLayout linearLayoutPlace1;
	public static LinearLayout linearLayoutPlace2;
	public static LinearLayout linearLayoutPlace3;
	public static LinearLayout linearLayoutPlace4;
	public static LinearLayout linearLayoutPlace5;
	public static LinearLayout linearLayoutPlace6;
	public static LinearLayout linearLayoutPlace7;
	public static LinearLayout linearLayoutPlace8;
	public static LinearLayout linearLayoutPlace9;
	public static LinearLayout linearLayoutPlace10;

	Button generalInfo;
	Button viewComments;
	Button moreInformation;
	Button back;

	public static boolean next = false;

	public static List<LinearLayout> linearLayoutPlaces = new ArrayList<LinearLayout>();
	public static List<Button> buttonPlaces = new ArrayList<Button>();
	public static List<ImageButton> imageButtonPlaces = new ArrayList<ImageButton>();

	TextView textViewPlace;

	boolean indoors = false;

	double radius;
	String featureCodes[];

	ProgressDialog myProgressDialog = null;
	private LocationListener gpsListener = new LocationListener() {

		public void onLocationChanged(Location location) {
			Log.e("Main", "***** Got first *****");
			curLocation = location;
			requestingPlaces();
		}

		public void onProviderDisabled(String provider) {
			Log.e("GPS Provider", "onProviderDisabled");
		}

		public void onProviderEnabled(String provider) {
			Log.e("GPS Provider", "onProviderEnabled");
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.e("GPS Provider", "onStatusChanged");
		}
	};

	public void requestingPlaces() {
		Thread thread = new Thread();
		thread = new Thread() {
			@Override
			public void run() {
				threadList.add(this);
				Log.e("Main", "thread added is: " + this.getId() + " "
						+ this.getName());
				Log.e("Main", "***** Got tanyyyy *****");
				GeonameClient fc = new GeonameClient();
				Log.e("Main","Radius is: "+radius);
				Vector<GeonameObject> vc = fc.getNearPlaces(curLocation,
						featureCodes, radius, 10, "no");
				Log.e("Main", "***** CurLocation LA:"
						+ curLocation.getLatitude() + " LO:"
						+ curLocation.getLongitude() + " *****");
				drawPlaces(vc);
			}
		};
		runOnUiThread(thread);
	}

	public static void drawPlaces(Vector<GeonameObject> vc) {
		Log.e("Main", "Views cleared from drawPlaces method");
		ar.clearARViews();
		if (vc != null && vc.size() > 0) {
			Enumeration e = vc.elements();
			while (e.hasMoreElements()) {
				GeonameObject fq = (GeonameObject) e.nextElement();
				Log.e("Main", "Got place:" + fq.name);
				if (fq.location != null)
					Log.i("Main", "Lat:" + fq.location.getLatitude() + ":"
							+ fq.location.getLongitude());
				Log.e("Main", "Azimuth: " + fq.azimuth);
				ar.addARView(fq);
			}
		}
	}

	private void addLoadingLayouts() {
		GeonameObject fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 0;
		fs.inclination = 0;
		fs.name = "Loading1";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 45;
		fs.inclination = 0;
		fs.name = "Loading2";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 90;
		fs.inclination = 0;
		fs.name = "Loading3";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 135;
		fs.inclination = 0;
		fs.name = "Loading4";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 150;
		fs.inclination = 0;
		fs.name = "Loading5";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 180;
		fs.inclination = 0;
		fs.name = "Loading6";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 210;
		fs.inclination = 0;
		fs.name = "Loading7";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 250;
		fs.inclination = 0;
		fs.name = "Loading8";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 280;
		fs.inclination = 0;
		fs.name = "Loading9";
		ar.addARView(fs);

		fs = new GeonameObject(this.getApplicationContext());
		fs.azimuth = 300;
		fs.inclination = 0;
		fs.name = "Loading10";
		ar.addARView(fs);

		ar.postInvalidate();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			firstlanch();

			ctx = this.getApplicationContext();

			// mainProcessing();

			curLocation = new Location("currentLocation");
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			requestWindowFeature(Window.FEATURE_NO_TITLE);

			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);

			ar = new ARLayout(getApplicationContext());

			cv = new CustomCameraView(this.getApplicationContext());
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			WindowManager w = getWindowManager();
			Display d = w.getDefaultDisplay();
			int width = d.getWidth();
			int height = d.getHeight();
			ar.screenHeight = height;
			ar.screenWidth = width;
			al = new AbsoluteLayout(getApplicationContext());
			rl = new FrameLayout(getApplicationContext());
			rl.addView(cv, width, height);
			rl.addView(al);
			addLoadingLayouts();
			Log.e("intentclass", getIntent().getClass().getName());
			Bundle bundle1 = getIntent().getExtras();
			placeLayout();
			extraInfoLayout();

			// drawLayout();
			String activity = bundle1.getString("Activity");
			if (activity.equals("layout"))
				getFilterResultsFromLayout();
			else if (activity.equals("capture"))
				getFilterResultsFromCapture();

			ar.debug = true;
			rl.addView(ar, width, height);

			setContentView(rl);

		} catch (Exception e) {
			Log.e("Main", "***** CATCH FROM MAIN CLASS *****");
		}

	}

	public void placeLayout() {
		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {
				buttonClicked = buttonPlaces.get(v.getId());
				Log.e("Main", "******Clicked " + buttonClicked.getText());

				transPanel.setVisibility(View.GONE);

				generalInfo.setVisibility(View.VISIBLE);
				viewComments.setVisibility(View.VISIBLE);
				moreInformation.setVisibility(View.VISIBLE);
				back.setVisibility(View.VISIBLE);
			}
		};

		// AbsoluteLayout.LayoutParams paramsButton = new
		// AbsoluteLayout.LayoutParams(15, 15, 0, 0);

		buttonPlace1Button = new Button(getApplicationContext());
		buttonPlace2Button = new Button(getApplicationContext());
		buttonPlace3Button = new Button(getApplicationContext());
		buttonPlace4Button = new Button(getApplicationContext());
		buttonPlace5Button = new Button(getApplicationContext());
		buttonPlace6Button = new Button(getApplicationContext());
		buttonPlace7Button = new Button(getApplicationContext());
		buttonPlace8Button = new Button(getApplicationContext());
		buttonPlace9Button = new Button(getApplicationContext());
		buttonPlace10Button = new Button(getApplicationContext());

		buttonPlace1Button.setText("Loading1");
		buttonPlace2Button.setText("Loading2");
		buttonPlace3Button.setText("Loading3");
		buttonPlace4Button.setText("Loading4");
		buttonPlace5Button.setText("Loading5");
		buttonPlace6Button.setText("Loading6");
		buttonPlace7Button.setText("Loading7");
		buttonPlace8Button.setText("Loading8");
		buttonPlace9Button.setText("Loading9");
		buttonPlace10Button.setText("Loading10");

		ImageButton imageButtonPlace1Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace2Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace3Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace4Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace5Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace6Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace7Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace8Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace9Button = new ImageButton(
				getApplicationContext());
		ImageButton imageButtonPlace10Button = new ImageButton(
				getApplicationContext());

		linearLayoutPlace1 = new LinearLayout(getApplicationContext());
		linearLayoutPlace2 = new LinearLayout(getApplicationContext());
		linearLayoutPlace3 = new LinearLayout(getApplicationContext());
		linearLayoutPlace4 = new LinearLayout(getApplicationContext());
		linearLayoutPlace5 = new LinearLayout(getApplicationContext());
		linearLayoutPlace6 = new LinearLayout(getApplicationContext());
		linearLayoutPlace7 = new LinearLayout(getApplicationContext());
		linearLayoutPlace8 = new LinearLayout(getApplicationContext());
		linearLayoutPlace9 = new LinearLayout(getApplicationContext());
		linearLayoutPlace10 = new LinearLayout(getApplicationContext());

		while (buttonPlaces.size() == 0) {
			Log.e("Main", "***** adding buttons *****");
			buttonPlaces.add(buttonPlace1Button);
			buttonPlaces.add(buttonPlace2Button);
			buttonPlaces.add(buttonPlace3Button);
			buttonPlaces.add(buttonPlace4Button);
			buttonPlaces.add(buttonPlace5Button);
			buttonPlaces.add(buttonPlace6Button);
			buttonPlaces.add(buttonPlace7Button);
			buttonPlaces.add(buttonPlace8Button);
			buttonPlaces.add(buttonPlace9Button);
			buttonPlaces.add(buttonPlace10Button);

			imageButtonPlaces.add(imageButtonPlace1Button);
			imageButtonPlaces.add(imageButtonPlace2Button);
			imageButtonPlaces.add(imageButtonPlace3Button);
			imageButtonPlaces.add(imageButtonPlace4Button);
			imageButtonPlaces.add(imageButtonPlace5Button);
			imageButtonPlaces.add(imageButtonPlace6Button);
			imageButtonPlaces.add(imageButtonPlace7Button);
			imageButtonPlaces.add(imageButtonPlace8Button);
			imageButtonPlaces.add(imageButtonPlace9Button);
			imageButtonPlaces.add(imageButtonPlace10Button);

			linearLayoutPlaces.add(linearLayoutPlace1);
			linearLayoutPlaces.add(linearLayoutPlace2);
			linearLayoutPlaces.add(linearLayoutPlace3);
			linearLayoutPlaces.add(linearLayoutPlace4);
			linearLayoutPlaces.add(linearLayoutPlace5);
			linearLayoutPlaces.add(linearLayoutPlace6);
			linearLayoutPlaces.add(linearLayoutPlace7);
			linearLayoutPlaces.add(linearLayoutPlace8);
			linearLayoutPlaces.add(linearLayoutPlace9);
			linearLayoutPlaces.add(linearLayoutPlace10);
		}

		for (int i = 0; i < buttonPlaces.size(); i++) {
			buttonPlaces.get(i).setId(i);
			buttonPlaces.get(i).setBackgroundColor(Color.TRANSPARENT);
			buttonPlaces.get(i).setTextColor(Color.WHITE);
			buttonPlaces.get(i).setTextSize(15);
			buttonPlaces.get(i).setTypeface(null,Typeface.BOLD);
			buttonPlaces.get(i).setOnClickListener(listener);

			imageButtonPlaces.get(i).setImageResource(
					android.R.drawable.ic_dialog_info);
			imageButtonPlaces.get(i).setBackgroundColor(Color.TRANSPARENT);
			imageButtonPlaces.get(i).setId(i);
			imageButtonPlaces.get(i).setOnClickListener(listener);

			linearLayoutPlaces.get(i).setOrientation(LinearLayout.VERTICAL);
			linearLayoutPlaces.get(i).setVisibility(View.GONE);
			linearLayoutPlaces.get(i).addView(imageButtonPlaces.get(i));
			linearLayoutPlaces.get(i).addView(buttonPlaces.get(i));
		}

		al.addView(linearLayoutPlace1);
		al.addView(linearLayoutPlace2);
		al.addView(linearLayoutPlace3);
		al.addView(linearLayoutPlace4);
		al.addView(linearLayoutPlace5);
		al.addView(linearLayoutPlace6);
		al.addView(linearLayoutPlace7);
		al.addView(linearLayoutPlace8);
		al.addView(linearLayoutPlace9);
		al.addView(linearLayoutPlace10);
	}

	public void extraInfoLayout() {
		comments += "Guest:\nThis book is a good reference for Java developers";
		comments += "\n\nProf Slim:\nI strongly recommend it\n";

		editText = new EditText(getApplicationContext());
		editText.setVisibility(View.GONE);

		addCommentButton = new Button(getApplicationContext());
		addCommentButton.setClickable(true);
		addCommentButton.setVisibility(View.GONE);
		addCommentButton.setText("Add Comment");
		addCommentButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				comments += "\nGuest: \n" + editText.getText() + "\nz";
				textView.setText(comments);
				editText.setText("");
			}
		});

		textView = new TextView(getApplicationContext());

		linearLayout = new LinearLayout(getApplicationContext());
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		linearLayout.addView(textView);
		linearLayout.addView(editText);
		linearLayout.addView(addCommentButton);

		scrollView = new ScrollView(getApplicationContext());
		scrollView.setBackgroundColor(Color.TRANSPARENT);
		scrollView.layout(0, 0, 300, 180);
		scrollView.setHorizontalScrollBarEnabled(true);
		scrollView.addView(linearLayout);

		AbsoluteLayout.LayoutParams paramsScroll = new AbsoluteLayout.LayoutParams(
				300, 180, 100, 70);
		scrollView.setLayoutParams(paramsScroll);

		transPanel = new TransparentPanel(getApplicationContext());
		transPanel.setVisibility(View.GONE);
		transPanel.addView(scrollView);

		AbsoluteLayout.LayoutParams paramsLayout = new AbsoluteLayout.LayoutParams(
				300, 180, 100, 70);

		transPanel.setLayoutParams(paramsLayout);

		al.addView(transPanel);

		OnClickListener moreInfobuttonsListener = new Button.OnClickListener() {
			public void onClick(View v) {
				Button moreInfobuttonClicked = (Button) v;
				Log.e("Main", "******Clicked "
						+ moreInfobuttonClicked.getText());

				editText.setVisibility(View.GONE);
				editText.setText("");
				addCommentButton.setVisibility(View.GONE);

				if (moreInfobuttonClicked == generalInfo) {
					textView.setText("GENERAL INFO :) "
							+ buttonClicked.getText());
				}

				if (moreInfobuttonClicked == viewComments) {
					textView.setText(comments);
					editText.setVisibility(View.VISIBLE);
					addCommentButton.setVisibility(View.VISIBLE);
				}

				if (moreInfobuttonClicked == moreInformation) {
					textView.setText("MORE INFORMATION :)"
							+ buttonClicked.getText());
				}

				if (moreInfobuttonClicked == back) {
					generalInfo.setVisibility(View.GONE);
					viewComments.setVisibility(View.GONE);
					moreInformation.setVisibility(View.GONE);
					back.setVisibility(View.GONE);
					transPanel.setVisibility(View.GONE);
					return;
				}
				transPanel.setVisibility(View.VISIBLE);
			}
		};

		AbsoluteLayout.LayoutParams paramsGeneralInfo = new AbsoluteLayout.LayoutParams(
				100, 50, 10, 265);
		generalInfo = new Button(getApplicationContext());
		generalInfo.setVisibility(View.GONE);
		generalInfo.setBackgroundColor(Color.GRAY);
		generalInfo.setText("General Informtion");
		generalInfo.setLayoutParams(paramsGeneralInfo);
		generalInfo.setOnClickListener(moreInfobuttonsListener);

		AbsoluteLayout.LayoutParams paramsComments = new AbsoluteLayout.LayoutParams(
				100, 50, 120, 265);
		viewComments = new Button(getApplicationContext());
		viewComments.setVisibility(View.GONE);
		viewComments.setBackgroundColor(Color.GRAY);
		viewComments.setText("Comments");
		viewComments.setLayoutParams(paramsComments);
		viewComments.setOnClickListener(moreInfobuttonsListener);

		AbsoluteLayout.LayoutParams paramsMoreInfo = new AbsoluteLayout.LayoutParams(
				100, 50, 230, 265);
		moreInformation = new Button(getApplicationContext());
		moreInformation.setVisibility(View.GONE);
		moreInformation.setBackgroundColor(Color.GRAY);
		moreInformation.setText("More Information");
		moreInformation.setLayoutParams(paramsMoreInfo);
		moreInformation.setOnClickListener(moreInfobuttonsListener);

		AbsoluteLayout.LayoutParams paramsBack = new AbsoluteLayout.LayoutParams(
				100, 50, 340, 265);
		back = new Button(getApplicationContext());
		back.setVisibility(View.GONE);
		back.setBackgroundColor(Color.GRAY);
		back.setText("Back");
		back.setLayoutParams(paramsBack);
		back.setOnClickListener(moreInfobuttonsListener);

		al.addView(generalInfo);
		al.addView(viewComments);
		al.addView(moreInformation);
		al.addView(back);
	}

	private void mainProcessing() {

		Thread thread = new Thread(null, doBackgroundProc, "Background2");

		thread.start();

		myProgressDialog = ProgressDialog.show(Main.this, "Please wait...",
				"Doing Extreme Calculations...", true);

	}

	private Runnable doBackgroundProc = new Runnable() {

		public void run() {

			backgroundProc();

		}

	};

	private void backgroundProc() {

		try {

			// Do some Fake-Work
			Log.e("Main", "in the working thread");

			Thread.sleep(2000);

		} catch (Exception e) {
			Log.e("Main", "in catch of backgroundProc");
		}

		myProgressDialog.dismiss();
	}

	public void firstlanch() {
		try {

			final String PACKAGE_NAME = "com.google.zxing.client.android";
			PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
					0);
			int currentVersion = info.versionCode;
			// Since we're paying to talk to the PackageManager anyway, it makes
			// sense to cache the app
			// version name here for display in the about box later.
			String versionName;
			versionName = info.versionName;
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(this);
			int lastVersion = prefs.getInt(
					PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
			if (currentVersion > lastVersion) {
				// prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN,
				// currentVersion).commit();
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
				// startActivity(intent);
				Log.e("Main", "FIRST TIME");
				return;
			} else
				Log.e("Main", "NOT FIRST TIME");
		} catch (PackageManager.NameNotFoundException e) {
			Log.w("main", e);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		Log.e("Main", "***** ONDESTROY after super *****");
		// thread.destroy();
		cv.closeCamera();
		ar.close();
		Log.e("Main", "thread List has: " + threadList.size());
		try {

			for (int i = 0; i < threadList.size(); i++) {
				// Thread a = threadList.get(0);
				Log.e("Main", "in main of destroying threads "
						+ threadList.get(i).getId() + " "
						+ threadList.get(i).getName());
				threadList.get(i).stop();
				// threadList.remove(0);

			}
			threadList.clear();
			Log.e("Main", "in main of destroying threads");
		} catch (Exception e) {
			Log.e("Main", "in catch of destroying threads");
		}
		// al.destroyDrawingCache();
		// cl.close();
		// cv.closeCamera();
		this.finish();
		try {
			this.finalize();
			Log.e("Main", "in finalize");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		LocationManager locMan = (LocationManager) ctx
				.getSystemService(Context.LOCATION_SERVICE);

		locMan.removeUpdates(gpsListener);

		al.destroyDrawingCache();
		rl.destroyDrawingCache();
		Intent intent = new Intent(getApplicationContext(), layout.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		android.os.Process.killProcess(android.os.Process.myPid());
		// this.moveTaskToBack(true);

		// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		// stopService(intent);

		Log.e("Main", "Stopped updates");

	}

	public void onStop() {
		super.onStop();

		Log.e("Main", "in stop application");

		try {
			// this.getIntent().addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			// Intent mainIntent= new
			// Intent(getApplicationContext(),Main.class);
			// mainIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			// mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// mainIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			this.finalize();
			Log.e("Main", "in stop application");
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void getFilterResultsFromLayout() {

		// addLoadingLayouts();
		Log.e("*******", getIntent().toString());

		Bundle bundle1 = getIntent().getExtras();
		if (bundle1 != null) {
			// String param1 = bundle1.getString("status");
			// Log.e("********",param1+"*******");
			Log.e("Main","Radius is when getting from layout: "+radius);
			radius = bundle1.getDouble("radius");
			ArrayList<String> fcodes = bundle1
					.getStringArrayList("FeatureCodes");
			if (fcodes != null) {
				featureCodes = new String[fcodes.size()];

				for (int i = 0; i < fcodes.size(); i++) {
					if (fcodes.get(i).equals("Buildings"))
						featureCodes[i] = "BLDG";
					else if (fcodes.get(i).equals("Cafeterias"))
						featureCodes[i] = "HUT";
					else if (fcodes.get(i).equals("Offices"))
						featureCodes[i] = "TWO ";
					else if (fcodes.get(i).equals("Class Rooms"))
						featureCodes[i] = "college ";
					else if (fcodes.get(i).equals("laboratories"))
						featureCodes[i] = "college ";
					else if (fcodes.get(i).equals("Sports Area"))
						featureCodes[i] = "AREA ";
					else if (fcodes.get(i).equals("Parking Area"))
						featureCodes[i] = "PRK ";
					
					Log.e("**Main****", fcodes.get(i));

				}

			} else {
				featureCodes = null;
				Log.e("***Main111***", "NO filteration selected");
			}
		} else {
			Log.e("Main", "Got nthg from layout !! ERROR");
		}

		LocationManager locMan = (LocationManager) ctx
				.getSystemService(Context.LOCATION_SERVICE);

		locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				(long) 10000, 3, gpsListener);

	}

	/**
	 * starts zxing app and sends the users filteration
	 */
	private void StartZebraCrossing() {
		Intent i = new Intent(getApplicationContext(), CaptureActivity.class);
		if (featureCodes != null) {
			for (int j = 0; j < featureCodes.length; j++) {
				Log.e("**Main222****", featureCodes[j]);
			}
		}
		// onStop();
		// startActivityForResult(i, 0);
		Bundle bundle1 = new Bundle();
		bundle1.putStringArray("featureCodes", featureCodes);
		i.putExtras(bundle1);
		indoors = true;
		setResult(RESULT_OK, i);
		startActivity(i);
		Log.e("*****", "in StartZebraCrossing");
		this.onDestroy();
		this.finish();
		// System.exit(0);

		// onActivityResult(requestCode, 2, i);
		// startActivity(i);

	}

	private void getFilterResultsFromCapture() {
		Bundle bundle1 = getIntent().getExtras();
		if (bundle1 != null) {
			featureCodes = bundle1.getStringArray("featureCodes");
			for (int j = 0; j < featureCodes.length; j++) {
				Log.e("**capture****", featureCodes[j]);
			}
			indoors = bundle1.getBoolean("indoors");
			String query = bundle1.getString("BarCodeContents");
			Log.e("Main", "query scanned is: " + query);
			// if(query.equals(null))
			if (query == null) {
				Log.e("Main", "query scanned is null");

				LocationManager locMan = (LocationManager) ctx
						.getSystemService(Context.LOCATION_SERVICE);

				locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
						10000, 1, gpsListener);
			} else
				handleScannedBarcode(query);
		}
	}

	private void handleScannedBarcode(String scanResult) {

		Log.e("Main", "query scanned is not null, scanResult :" + scanResult);
		if (scanResult != null) {
			try {
				Log.e("Main", "***** Zebra Crossing scanned " + scanResult
						+ " *****");
				String[] tokens = scanResult.split("[?]");
				String[] LatLng = tokens[0].substring(4).split(",");
				String query = tokens[1].substring(2);
				Log.e("Main, handleScannedBarcode()", "LatLng: \"" + LatLng[0]
						+ "\" , \"" + LatLng[1] + "\" and query: \"" + query
						+ "\"");

				// double lat = Double.valueOf(scanResult.substring(4, 12));
				// double lng = Double.valueOf(scanResult.substring(13, 21));
				// String query = scanResult.substring(24);

				double lat = Double.valueOf(LatLng[0]);
				double lng = Double.valueOf(LatLng[1]);
				curLocation.setLatitude(lat);
				curLocation.setLongitude(lng);
				Log.e("Main", "curLocation.setLatitude(lat);"
						+ curLocation.getLatitude()
						+ " curLocation.setLongitude(lng);"
						+ curLocation.getLongitude());
				Log.e("Main", "after setting lng and lat");

				GeonameObject nearPlace = new GeonameObject(Main.ctx);
				Vector<GeonameObject> v = new Vector<GeonameObject>();
				getNearbyPlaces(query);
			} catch (Exception e) {
				Log.e("****", "Catch");
			}
		}
	}

	public void getNearbyPlaces(final String query) {
		Thread thread = new Thread() {
			@Override
			public void run() {
				threadList.add(this);
				Log.e("Main", "thread added is: " + this.getId() + " "
						+ this.getName());
				Log.e("Main", "***** Got tanyyyy *****");
				GeonameClient fc = new GeonameClient();
				Vector<GeonameObject> vc = fc.getNearPlaces(curLocation,
						featureCodes, radius, 10,query);
				Log.e("Main", "***** CurLocation LA:"
						+ curLocation.getLatitude() + " LO:"
						+ curLocation.getLongitude() + " *****");
				if (vc.size() > 0) {
					connected = true;
					drawPlaces(vc);
				}
			}
		};
		runOnUiThread(thread);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		menu.add(0, 0, 0, "Sign Out").setIcon(
				android.R.drawable.ic_menu_info_details);

		menu.add(0, 1, 0, "Refresh").setIcon(android.R.drawable.ic_menu_rotate);
		if (!indoors)
			menu.add(0, 2, 0, "Indoor Mode").setIcon(R.drawable.barcode);
		else
			menu.add(0, 2, 0, "Outdoor Mode").setIcon(
					android.R.drawable.ic_menu_compass);
		menu.add(0, 3, 0, "Exit").setIcon(android.R.drawable.ic_lock_power_off);
		menu.add(0, 4, 0, "Help").setIcon(android.R.drawable.ic_menu_help);
		menu.add(0, 5, 0, "Re-filter");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		// Thread thread = new Thread();
		// thread = new Thread() {
		// @Override
		// public void run() {
		switch (item.getItemId()) {
		case 0: {
			menuSignout();
			break;
		}
		case 1: {
			if (curLocation != null)
				requestingPlaces();
			// else{}
			break;
		}
		case 2: {
			if (!indoors)
				StartZebraCrossing();
			else {
				indoors = false;
				item.setTitle("Indoor Mode");
				LocationManager locMan = (LocationManager) ctx
						.getSystemService(Context.LOCATION_SERVICE);

				locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
						10000, 1, gpsListener);
			}

			break;
		}
		case 3: {
			onDestroy();

			break;
		}
		case 4:
			// Toast.makeText(Main.this, "Helpppppp!!",
			// Toast.LENGTH_SHORT).show();
			mainProcessing();

			break;
		case 5:
			refiltering();
		}
		// }
		// };
		// runOnUiThread(thread);
		return super.onOptionsItemSelected(item);
	}

	private void menuSignout() {
		Intent i = new Intent(ctx, layout.class);
		setResult(RESULT_OK, i);
		startActivity(i);
		this.onDestroy();
	}

	private void refiltering() {
		Intent i = new Intent(ctx, layout.class);
		i.putExtra("Activity", "Main");
		setResult(RESULT_OK, i);
		startActivity(i);
		this.onDestroy();
	}
}
